
import React from 'react'
import errorMessage from 'share/errorMessage';
import { messages, getApprovelHistory } from 'share/common'
import { Form, Icon, Timeline, Row, Col, Tag , Modal, Button, Input} from 'antd';
const {TextArea} = Input;
const FormItem = Form.Item;
import expenseReportService from 'containers/expense-report/expense-report.service'
import approveService from 'containers/approve/approve.service'

import moment from 'moment'
import 'styles/components/template/approve-history.scss'
import { connect } from 'react-redux'
import {message} from "antd/lib/index";

class ApproveHistory extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputVisible:false,
      loading:false,
      forReplyInfo:{},
      approvalNodeList: [], //approvalChains, approvalHistory里的节点列表
      futureNodeList: [], //未来节点
      loadingFuture: false, //加载未来节点
      isShowFutureNode: false, //是否展示未来节点
      // hasFutureNode: false, //是否有未来节点
    }
  }

  componentDidMount() {
    // 审批历史节点名称下线
    // const { approvalHistory, approvalChains } = this.props;
    // let nodeOIDList = [];
    // approvalChains && approvalChains.map(chain => {
    //   if (chain.ruleApprovalNodeOID) {
    //     nodeOIDList.addIfNotExist(chain.ruleApprovalNodeOID);
    //   }
    // });
    // approvalHistory && approvalHistory.map(history => {
    //   if (history.ruleApprovalNodeOID) {
    //     nodeOIDList.addIfNotExist(history.ruleApprovalNodeOID);
    //   }
    // });
    // if (nodeOIDList.length) {
    //   approveService.getApproveNodeName(nodeOIDList).then(resq => {
    //     this.setState({approvalNodeList: resq.data ? resq.data : []});
    //   }).catch(err => {
    //     errorMessage(err.response);
    //   });
    // }
    // console.log('=======23424=====');
    // this.hasFutureNode();
  };

  //财务答复
  handleInputConfirm = () => {
    let {forReplyInfo} = this.state;
    let {user,approvalHistory,businessCode} = this.props;
    let values = this.props.form.getFieldsValue();
    if (values.reply) {
      if (values.reply.trim() && values.reply.trim().length <= 80) {
        let params = {
          billOID: forReplyInfo.entityOID,
          businessCode: businessCode,
          toUserOID: forReplyInfo.operatorOID,
          fromUserOID: user.userOID,
          type: forReplyInfo.entityType,
          remark: values.reply.trim()
        };
        this.setState({loading: true});
        expenseReportService.replyComment(params).then(res => {
          this.setState({loading: false,inputVisible:false});
          let replyInfo = {
            createdDate:new Date(),
            operation: 8001,
            operationDetail: values.reply.trim(),
            operator:{
              fullName:user.fullName,
              employeeID:user.employeeID
            }
          };
          approvalHistory.unshift(replyInfo);
          this.setState({loading: false,inputVisible:false});
          message.success(messages("common.operate.success")/*操作成功*/);
        }).catch(e => {
          this.setState({loading: false});
          message.error(messages('common.operate.filed'));
        });
      } else {
        message.error(messages('common.max.characters.length', {max: 80}));
      }
    } else {
      message.error(messages('common.please.input'));
    }
  };

  renderOperationDetail = (operationDetail, operation) => {
    //5010审批人转交
    //5011管理员转交
    if (operation === 5010 || operation === 5011) {
      operationDetail = `${messages('components.key949')/*转交意见：*/}${operationDetail}`;
    }
    operationDetail && (operationDetail = operationDetail.replace('\\r\\n','<br/>'));

    // 审批历史里，确认或拒绝的审批意见不显示
    (operationDetail === 'CP:' || operationDetail === 'CR:') && (operationDetail = '');
    return (
      <div style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{__html: operationDetail}} />
    )
  };

  getFutureNode = () => {
    const { approvalChains } = this.props;
    const { futureNodeList } = this.state;
    let params = {
      entityOID: approvalChains[0].entityOID,
      entityType: approvalChains[0].entityType,
      currentNodeOID: approvalChains[0].ruleApprovalNodeOID
    };
    this.setState({loadingFuture: true});
    if (futureNodeList && futureNodeList.length) {
      this.setState({loadingFuture: false, isShowFutureNode: true});
    } else {
      approveService.getFutureNode(params).then(res => {
        if (res.data) {
          this.setState({futureNodeList: res.data.reverse()});
        }
      }).catch(e => {
        message.error(messages('common.operate.filed'));
      }).finally(() => {
        this.setState({loadingFuture: false, isShowFutureNode: true});
      });
    }
  };

  hideFutureNode = () => {
    this.setState({isShowFutureNode: false});
  };

  //是否是新版审批流，只有新版审批流才有查看未来节点
  isShowModeCopy = () => {
    const { approvalChains } = this.props;
    let version = approvalChains[0].version;
    let isShow = false;
    if (version && Number(version.split('.')[0]) > 0) {
      isShow = true;
    }
    return isShow;
  };

  //是否有未来节点
  // hasFutureNode = () => {
  //   const { approvalChains } = this.props;
  //   const { futureNodeList } = this.state;
  //   let params = {
  //     entityOID: approvalChains[0].entityOID,
  //     entityType: approvalChains[0].entityType,
  //     currentNodeOID: approvalChains[0].ruleApprovalNodeOID
  //   };
  //
  //   if (futureNodeList && futureNodeList.length) {
  //     this.setState({hasFutureNode: true});
  //   } else {
  //     approveService.getFutureNode(params).then(res => {
  //       if (res.data && res.data.length) {
  //         this.setState({hasFutureNode: true});
  //       } else {
  //         this.setState({hasFutureNode: false});
  //       }
  //     }).catch(e => {
  //       this.setState({hasFutureNode: false});
  //     });
  //   }
  // };

  renderNodeName = (nodeOID) => {
    // 审批历史节点名称下线
    // const { approvalNodeList } = this.state;
    // let nodeName = '';
    // approvalNodeList.map(node => {
    //   if (node.ruleApprovalNodeOID === nodeOID) {
    //     nodeName = node.name;
    //   }
    // });
    // return nodeName ? (<span>{nodeName}:&nbsp;</span>) : <span/>
    return null;
  };

  render() {
    const { approvalChains, approvalHistory, applicantInfo,isShowReply, needApplicantConfirm, formCode, type } = this.props;
    const { loading, inputVisible, loadingFuture, futureNodeList, isShowFutureNode } = this.state;
    const { getFieldDecorator } = this.props.form;
    console.log('approvalHistory', approvalHistory)
    return (
      <div className="approve-history">
        {approvalChains && !!approvalChains.length && this.isShowModeCopy() && (
          <div className="next-block">
            {!isShowFutureNode && (
              <span className={`btn ${loadingFuture ? 'disabled' : ''}`} onClick={!loadingFuture && this.getFutureNode}> {messages('components.key916')/*查看未来节点*/}
              </span>
            )}
            {isShowFutureNode && (
              <span className="btn" onClick={!loadingFuture && this.hideFutureNode}> {messages('components.key917')/*收起未来节点*/}
              </span>
            )}
          </div>
        )}
        <Timeline>
          {isShowFutureNode && !!futureNodeList.length && futureNodeList.map(node => {
            return (
              <Timeline.Item className="first-item" color="#d4d4d4">
                <Row>
                  <Col span={3} offset={3} className="operation-type">{node.operationDescription}</Col>
                  <Col span={17} className="operation-name">
                    {/*{node.nodeApproverDescription ? `: ${node.nodeApproverDescription}` : ''}*/}
                    {
                      node.nodeApprover && node.nodeApprover.length > 0 ? node.nodeApprover.map((approver, i) => {
                        const {contact={}} = approver || {};
                        return (
                          <p key={i}>
                            {node.remark ? `${node.remark} ` : ''}
                            {node.fullName && node.remark ? ('：') : ''}
                            {contact.fullName} {contact.employeeID}
                            {contact.departmentName ? ` | ${contact.departmentName}` : ''}
                            {contact.title ? ` | ${contact.title}` : ''}
                            {/* {i < node.nodeApprover.length - 1 && <span style={{color: '#000'}}> & </span>} */}
                          </p>
                        )
                      }) : <p>{node.remark}</p>
                    }
                  </Col>
                </Row>
              </Timeline.Item>
            )
          })}
          {approvalChains && approvalChains.length && (
            <Timeline.Item className="first-item" color="#d4d4d4">
              <Row>
                <Col span={3}>{moment(approvalChains[0].lastModifiedDate).format('YYYY-MM-DD HH:mm')}</Col>
                <Col span={3} className="operation-type">{type === 'expense' ? messages(needApplicantConfirm ? 'common.await.confirm'/*等待确认*/ : approvalChains[0].brmsRemark === '财务预审' || approvalChains[0].brmsRemark === '财务复审' ? (approvalChains[0].brmsRemark === '财务预审' ? 'components.key1368'/*等待预审*/ : 'components.key1369'/*等待复审*/) : 'components.key431'/*等待审批*/) : messages(needApplicantConfirm ? 'common.await.confirm'/*等待确认*/ : approvalChains[0].brmsRemark === '财务预审' || approvalChains[0].brmsRemark === '财务复审' ? 'components.key1350'/*等待审核*/ : 'components.key431'/*等待审批*/)}</Col>
                <Col span={17} className="operation-name">
                  {approvalChains.map((chain, index) => {
                    return chain.proxyApprovers && chain.proxyApprovers.length ? (
                      <div key={index} style={{float: 'left'}}>
                        {this.renderNodeName(chain.ruleApprovalNodeOID)}
                        {chain.proxyApprovers.map((proxy, i) => {
                          return (
                            <span key={i}>
                                {proxy.fullName} {proxy.employeeID}
                              {proxy.departmentName ? ` | ${proxy.departmentName}` : ''}
                              {proxy.title ? ` | ${proxy.title}` : ''}
                              {i < chain.proxyApprovers.length - 1 && <span style={{color: '#000'}}> & </span>}
                              </span>
                          )
                        })}
                        &nbsp;({messages('components.key659',{arg1: chain.approverName,arg2: chain.approverEmployeeID}/*代理 {arg1} {arg2} 审批*/)})
                        {index < approvalChains.length - 1 && <span style={{color: '#000'}}>&nbsp;|&nbsp;</span>}
                      </div>
                    ) : (
                      <div key={index} style={{float: 'left'}}>
                        {chain.brmsRemark && chain.approverName ? <span>{chain.brmsRemark + '：'}</span> : <span>{chain.brmsRemark}</span>}
                        {this.renderNodeName(chain.ruleApprovalNodeOID)}
                        {chain.approverName} {chain.approverEmployeeID}
                        {chain.departmentName ? ` | ${chain.departmentName}` : ''}
                        {chain.title ? ` | ${chain.title}` : ''}
                        {index < approvalChains.length - 1 && <span style={{color: '#000'}}>&nbsp;|&nbsp;</span>}
                      </div>
                    )
                  })}
                </Col>
              </Row>
            </Timeline.Item>
          )}
          {approvalHistory && approvalHistory.map(item => {
            return item.operation === 5009 ? '' : (
            // return (
              <Timeline.Item key={item.id} dot={
                item.operation === 5009 ?
                <div className="timeline-icon-my"><div>
                  {messages('components.key432'/*我的*/)}</div>
                </div> :
                (getApprovelHistory(item.operation).icon ? <Icon type={getApprovelHistory(item.operation).icon} style={{color: getApprovelHistory(item.operation).color}}/> : null)
                }>
                <Row>
                  <Col span={3}>{moment(item.createdDate).format('YYYY-MM-DD HH:mm')}</Col>
                  {/*审批通过有三种情况：审批通过、自审批通过、加签 审批通过*/}
                  {item.operation === 2001 && (
                    <Col span={3} className="operation-type">
                      {item.operationType === 1001 && (messages('components.key433'/*自审批通过*/))}
                      {item.operationType !== 1001 && (
                        <span>
                            {(item.countersignType === 1 || item.countersignType === 2) && formCode !== 'MCD3001' && (
                              ` ${messages('components.key434'/*加签*/)} `
                            )}
                            {item.operationDetail === 'CP:' ? messages('common.order.confirm'/*确认订单*/) : (item.operationDetail === 'CR:' ? messages('common.order.refuse'/*拒绝订单*/) : item.operationDescription)}
                        </span>
                      )}
                    </Col>
                  )}
                  {item.operation !== 2001 && (
                    <Col span={3} className="operation-type">
                      {item.operationDetail === 'CP:' ? messages('common.order.confirm'/*确认订单*/) : (item.operationDetail === 'CR:' ? messages('common.order.refuse'/*拒绝订单*/) : item.operationDescription)}
                     </Col>
                  )}
                  {/*企业关闭不展示操作者*/}
                  {item.operation !== 5005 && (
                    <Col span={17} className="operation-name">
                      {/*如果有审批节点的话，展示节点名称*/}
                      {this.renderNodeName(item.ruleApprovalNodeOID)}
                      {item.brmsRemark && <span>{item.brmsRemark + '：'}</span>}
                      {/*流程人员信息*/}
                      {item.role ?
                        `${item.role} ${<span className="ant-divider"/>} ` : ''} {item.operator?`${item.operator.fullName === '麦当劳' && [4000, 4001].includes(item.operation) ? '' : item.operator.fullName} ${item.operator.employeeID ? item.operator.employeeID === '9999999999' && [4000, 4001].includes(item.operation) ? '' : item.operator.employeeID : ''}`: ''}
                      {item.operator && item.operator.departmentName ? ` ${item.operator.fullName === '麦当劳' && [4000, 4001].includes(item.operation) ? '' : '|'} ${item.operator.fullName === '麦当劳' && [4000, 4001].includes(item.operation) ? '' : item.operator.departmentName}` : ''}
                      {item.operator && item.operator.title && !(item.operator.fullName === '麦当劳' && [4000, 4001].includes(item.operation)) ? ` | ${item.operator.title}` : ''}

                      {/*代理审批*/}
                      {item.chainApprover && item.chainApprover.fullName && (item.operation === 2001 || item.operation === 2002) &&
                      item.operator.employeeID !== item.chainApprover.employeeID && (
                        ` (${messages('components.key659',{arg1:item.chainApprover.fullName,arg2: item.chainApprover.employeeID || ''}/*代理 {arg1} {arg2} 审批*/)})`
                      )}

                      {/*代理制单*/}
                      {item.operation === 1001 && applicantInfo.userOID && applicantInfo.userOID !== item.operator.userOID
                      && item.operator.userOID !== '00000000-0000-0000-0000-000000000001' && (
                        ` (${messages('components.key435'/*代理*/)} ${applicantInfo.fullName} ${applicantInfo.employeeID || ''})`
                      )}
                    </Col>
                  )}
                </Row>
                <Row style={{color: (item.operation === 2003 || item.operation === 2002 || item.operation === 3002) ? '#E57670' : '#666', wordWrap:'break-word'}}>
                  <Col span={3}>
                    {!!item.apportionmentFlag && <Tag color="blue">{messages('components.key436'/*分摊审批*/)}</Tag>}
                  </Col>
                  <Col span={21}>
                    {/*审批转交的审批历史*/}
                    {/*5010审批人转交  5011管理员转交*/}
                    {(item.operation === 5010 || item.operation === 5011) && item.transferrePerson && (
                      <Row> {messages('components.key950')/*转交给：*/}{item.transferrePerson.fullName}&nbsp;{item.transferrePerson.employeeID}
                      </Row>
                    )}
                    <Row>
                      {this.renderOperationDetail(item.operationDetail, item.operation)}
                      {/*财务通知回复*/}
                      {/*{item.operation === 3006 && isShowReply ?*/}
                        {/*<span><br/><a onClick={()=>{this.setState({inputVisible:true,forReplyInfo:item})}}>{messages('components.key437')}</a></span> : ''}*/}
                    </Row>
                    {
                      item.operationCreditRule &&
                      <Row>
                        <Col span={2}>{messages('components.key706')/*信用事件*/}：</Col>
                        <Col span={16} style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{__html: item.operationCreditRule}}></Col>
                      </Row>
                    }
                    <Row>
                      {(item.operation === 7001 || item.operation === 7002 || item.operation === 7003) && item.remark}
                    </Row>
                  </Col>
                </Row>
              </Timeline.Item>
            )
          })}
        </Timeline>
        {/*员工答复弹框MODAL*/}
        <Modal title={messages('components.key437'/*回复*/)} visible={inputVisible}
               onCancel={() => {
                 this.setState({inputVisible: false})
               }} maskClosable={false} destroyOnClose={true}
               footer={[
                 <Button key="back" onClick={() => {
                   this.setState({inputVisible: false})
                 }}>{messages('common.cancel')/*取消*/}</Button>,
                 <Button key="submit" htmlType="submit" type="primary" loading={loading}
                         onClick={this.handleInputConfirm}>{messages('common.ok')/*确定*/}</Button>
               ]}
        >
          <Form>
            <FormItem>
              {getFieldDecorator('reply', {
                initialValue: ''
              })(
                <TextArea placeholder={messages('common.max.characters.length', {max: 80})}
                          rows={6}
                          style={{resize: 'none'}}/>
              )}
              <div style={{textAlign: 'right'}}>
                {this.props.form.getFieldValue('reply').trim().length} / 80
              </div>
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

ApproveHistory.propTypes = {
  approvalChains: React.PropTypes.array,  //审批链
  approvalHistory: React.PropTypes.array,  //审批历史
  applicantInfo: React.PropTypes.object,  //申请人信息
  businessCode: React.PropTypes.string,//单号,用于员工答复
  formCode: React.PropTypes.string,//表单编码
  isShowReply: React.PropTypes.bool,//是否显示回复，单据查看的视角不同
  needApplicantConfirm: React.PropTypes.bool,//是否需要确认
};

ApproveHistory.defaultProps={
  approvalChains: [],
  approvalHistory: [],
  applicantInfo: {},
  isShowReply: false,
  needApplicantConfirm: false,
};

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}
const WrappedApproveHistory = Form.create()(ApproveHistory);

export default connect(mapStateToProps)(WrappedApproveHistory);
